package com.dats.util;


import com.dats.db.DatS;
import com.dats.pool.DatSPool;

import java.util.List;
import java.util.Map;

/**
 * @author sig
 * @since 2016/10/4
 */
public class TableUtil {

    public static void buildTable(String parent, String name,
                                  boolean classShow, boolean addShow) {
        if (null != name && !"".equals(name.trim())) {
            SqlUtil.build(parent, name, classShow, addShow);
        } else {
            List<String> baseNameList = getTableNameList(DatSPool.baseAlias);
            List<String> userNameList = getTableNameList(DatSPool.userAlias);
            List<String> fileList = SqlUtil.getFileList(parent);

            for (String fileName : fileList) {

                if (null == fileName || fileName.contains("~$"))
                    continue;
                String tableName = SqlUtil.format(fileName);
                boolean exist;

                if (fileName.startsWith("base")) {
                    exist = baseNameList.contains(tableName);
                } else {
                    exist = userNameList.contains(tableName);
                }
                if (exist) {
                    String sql = getCreateSql(tableName);
                    SqlUtil.build(parent, tableName, sql);
                } else {
                    SqlUtil.build(parent, tableName, classShow, addShow);
                }
            }
        }
        System.out.println("Completed.");
    }

    private static List<String> getTableNameList(String alias) {
        String sql = "SHOW TABLES;";
        return DatS.loadStringList(alias, sql);
    }

    private static String getCreateSql(String tableName) {
        tableName = SqlUtil.format(tableName);
        String alias;

        if (tableName.startsWith("base")) {
            alias = DatSPool.baseAlias;
        } else {
            alias = DatSPool.userAlias;
        }
        String sql = "SHOW CREATE TABLE `" + tableName + "`";
        Map<String, Object> map = DatS.loadMap(alias, sql);

        if (null == map || null == map.get("Create Table"))
            throw new RuntimeException("The " + tableName + " Create Table is null");
        return map.get("Create Table").toString();
    }
}
